package org.ws.httphelper.servlet;

import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.resource.PathResource;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 *
 * https://www.eclipse.org/jetty/documentation/current/embedded-examples.html
 *
 */
public class JettyServlet {

    private final Server server;
    private static final AtomicBoolean running = new AtomicBoolean(false);

    public JettyServlet(int port) {
        server = new Server(port);
    }

    private void init() throws Exception{
        ServletContextHandler context1 = new ServletContextHandler();
        context1.setContextPath("/");
        // GET,POST,PUT,DELETE
        context1.addServlet(new ServletHolder(new TestApiServlet()),"/test");

        // 静态资源
        // 测试获取html用于解析
        // 测试下载
        Path path = Paths.get(JettyServlet.class.getResource("/servlet/").toURI());
        PathResource baseResource = new PathResource(path);
        context1.addServlet(new ServletHolder(new DefaultServlet()),"/*");
        context1.setBaseResource(baseResource);

        server.setHandler(context1);
    }

    public void start() throws Exception {
        if(!running.get()) {
            running.set(true);
            init();
            server.start();
        }
    }


    public static void main(String [] args) throws Exception {
        JettyServlet servlet = new JettyServlet(8888);
        servlet.start();
    }

}
